package cn.edu.shou.lab.config.utils;

import cn.edu.shou.lab.config.query.Retrieval;
import org.springframework.data.domain.Pageable;

import java.util.List;

public class SimpleSqlBuilder {

    private String tableName;
    private List<Retrieval> conditions;
    private Pageable pageable;

    private StringBuilder sb;

    public SimpleSqlBuilder(String sql, Pageable pageable) {
        this.pageable = pageable;
        this.sb = new StringBuilder(sql);
        setPageable();
    }

    public SimpleSqlBuilder(String tableName, List<Retrieval> conditions, Pageable pageable) {
        this.tableName = tableName;
        this.conditions = conditions;
        this.pageable = pageable;
        this.sb = new StringBuilder("select * from " + tableName + " where 1=1 ");
        appendCondition();
        setPageable();
    }

    public String getSql(){
        return sb.toString();
    }

    private void appendCondition(){
        for(Retrieval retrieval : conditions){
            sb.append(" and ");
            if(retrieval.getMode().equals("0")){
                sb.append(retrieval.getName() + "='" + retrieval.getValue() + "' ");
            }else if(retrieval.getMode().equals("1")){
                sb.append(retrieval.getName() + " like '" + retrieval.getValue() + "%' ");
            }else if(retrieval.getMode().equals("2")){
                sb.append(retrieval.getName() + " like '%" + retrieval.getValue() + "' ");
            }else if(retrieval.getMode().equals("3")){
                sb.append(retrieval.getName() + " like '%" + retrieval.getValue() + "%' ");
            }
        }
    }

    private void setPageable(){
        if(pageable == null){
            return;
        }
        int left = pageable.getPageSize() * (pageable.getPageNumber() - 1);
        int right = pageable.getPageSize();
        sb.append(" limit " + left + "," + right);
    }
}
